<template>
  <!-- 添加或修改采购发票对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="100%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-row :gutter="20">
      <el-col :span="5">
        <el-card class="box-card">
          <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="80px">
            <el-form-item label="发票编号" prop="invoiceCode" >
              <el-input v-model="form.invoiceCode" placeholder="请输入发票编号" style="width: 240px;"/>
            </el-form-item>
            <el-form-item label="发票金额" prop="totalAmount">
              <el-input-number v-model="form.totalAmount" placeholder="请输入金额" :min="0"/>
            </el-form-item>
            <el-form-item label="开票时间" prop="invoiceDate">
              <el-date-picker clearable
                              v-model="form.invoiceDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择开票时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择供应商" filterable remote reserve-keyword
                         :remote-method="searchSupplier" :loading="loadingSupplier" style="width: 240px;">
                <el-option v-for="item in optionsSupplier"
                           :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>

            <el-form-item label="发票文件" prop="invoiceFile">
              <file-upload-invoice @getInvoiceInfo="getInvoiceInfo" v-model="form.invoiceFile" :limit="1"/>
            </el-form-item>
            <span style="color: red;font-size: 16px;">票面金额：{{form.amount}}</span>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="19">
        <el-card class="box-card">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"
                   label-width="90px">
            <el-form-item label="采购单号" prop="caigouno">
              <el-input v-model="queryParams.caigouno" placeholder="请输入采购单号"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="到货单号" prop="daohuono">
              <el-input v-model="queryParams.daohuono" placeholder="请输入到货单号"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="入库单号" prop="nos">
              <el-input v-model="queryParams.nos" placeholder="请输入单据号"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="产品编码" prop="code">
              <el-input v-model="queryParams.code" placeholder="请输入产品编码"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="产品名称" prop="goodsName">
              <el-input v-model="queryParams.params['goodsName']" placeholder="请输入产品名称"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="产品型号" prop="goodsModel">
              <el-input v-model="queryParams.params['goodsModel']" placeholder="请输入产品型号"
                        clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item>
              <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAddStoreList">添加</el-button>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="detailListLoading" :data="buyStoreDetailList" @selection-change="handleSelectionChange"
                    ref="table" show-summary :summary-method="getSummaries" :max-height="tableMaxHeight">
            <el-table-column type="selection" width="60" align="center"/>
            <el-table-column sortable label="采购单号" align="center" prop="caigouno"/>
            <el-table-column sortable label="到货单号" align="center" prop="daohuono"/>
            <el-table-column sortable label="入库单号" align="center" prop="nos"/>
            <el-table-column label="产品编码" align="center" prop="code"/>
            <el-table-column label="产品名称" align="center" prop="params.goodsName"/>
            <el-table-column label="产品型号" align="center" prop="params.goodsModel"/>
            <el-table-column label="产品数量" align="center" prop="daohuoCount"/>
            <el-table-column label="重量" align="center" prop="dun"/>
            <el-table-column label="单价" align="center" prop="goodsBuyPrice"/>
            <el-table-column label="总价" align="center" prop="goodsBuyTotal"/>
            <el-table-column label="入库日期" align="center" prop="rukudate" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.rukudate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="入库人" align="center" prop="rukuren"/>
            <el-table-column label="开票剩余" align="center" prop="invoiceRemain"/>
            <el-table-column label="开票金额" align="center" prop="invoiceTemp" width="160" fixed="right">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.invoiceTemp" size="mini"
                                 :max="scope.row.invoiceRemain"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getBuyStoreDetailList"/>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-card class="box-card">
        <el-table v-loading="invoiceRukuRelLoading" :data="invoiceRukuRelList"
                  show-summary :summary-method="getSummariesRel" ref="relTable">
          <el-table-column label="序号" align="center" type="index"/>
          <el-table-column label="发票编号" align="center" prop="invoiceCode"/>
          <el-table-column label="入库单编号" align="center" prop="storeNos"/>
          <el-table-column label="产品名称" align="center" prop="goodsName"/>
          <el-table-column label="产品编号" align="center" prop="goodsCode"/>
          <el-table-column label="产品型号" align="center" prop="goodsModel"/>
          <el-table-column label="金额" align="center" prop="amount"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-popconfirm :title="`确认删除当前数据项？`" @confirm="handleDeleteRel(scope.row)"
                             style="margin-left: 10px;">
                <el-button slot="reference" size="mini" type="text" icon="el-icon-delete"
                           v-hasPermi="['develop:FinanceBuyInvoiceStoreRel:remove']">删除
                </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

  </el-dialog>
</template>

<script>
import {accAdd, addAction, deleteAction, getAction, getById, isEmpty, postAction, updateAction} from '@/api/manage';
import moment from 'moment';
import {parseDate} from "echarts/lib/util/number";
import {parseTime} from "@/utils/ruoyi";

export default {
  name: "FinanceBuyInvoiceForm",
  dicts: ['churuku_type', 'caigou_type', 'storage_state', 'ruku_source'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nos: null,
        projectId: null,
        projectNo: null,
        code: null,
        customerName: null,
        saleName: null,
        isZhijian: null,
        parentId: null,
        orderByColumn: "create_time",
        isAsc: "desc",
        params: {},
      },
      relQueryParams:{
        status:null,
        pageSizeZero:true,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        supplierId: [{required: true, message: "请选择供应商", trigger: "blur"}],
        invoiceCode: [{required: true, message: "请输入发票编号", trigger: "blur"}],
        invoiceDate: [{required: true, message: "请选择开票时间", trigger: "blur"}],
        totalAmount: [{required: true, message: "开票金额不能为空", trigger: "blur"},
          {validator: this.moneyValidator, trigger: 'blur'}],
        invoiceFile: [{required: true, message: "请上传开票文件", trigger: "blur"}],
      },
      loadingSupplier: false,
      detailListLoading: false,
      optionsSupplier: [],
      buyStoreDetailList: [],
      selectRows: [],
      invoiceRukuRelLoading:false,
      invoiceRukuRelList: [],
      url: {
        getById: '/financeBuyInvoice/financeBuyInvoice/',
        add: '/financeBuyInvoice/financeBuyInvoice/add',
        edit: '/financeBuyInvoice/financeBuyInvoice/edit',
        buyStoreDetailList: '/lvRukumingxi/lvRukumingxi/buyNotInvoiceList',
        addRukumingxiList: '/financeBuyInvoiceStoreRel/financeBuyInvoiceStoreRel/addRukumingxiList',
        invoiceRukuRelList: '/financeBuyInvoiceStoreRel/financeBuyInvoiceStoreRel/list',
        removeRel: '/financeBuyInvoiceStoreRel/financeBuyInvoiceStoreRel/',
      },
      tableMaxHeight: window.innerHeight - 320,
    };
  },
  created() {

  },
  methods: {
    moneyValidator(rule, value, callback) {
      if (value === 0) {
        callback(new Error('付款金额不能为0'));
      } else {
        callback();
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        invoiceCode: null,
        invoiceFile: null,
        money: null,
        invoiceDate: null,
        supplierId: null,
        supplierName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getBuyStoreDetailList();
      this.relQueryParams.status="0";
      this.getInvoiceRukuRelList();
      this.open = true;
      this.title = "添加采购发票";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getById(this.url.getById, id).then(response => {
        this.form = response.data;
        this.invoiceRukuRelList = response.data.invoiceRukuRelList;
        this.open = true;
        this.title = "修改采购发票";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(this.invoiceRukuRelList.length===0){
        this.$modal.msgError("请选择入库明细");
        return;
      }
      this.form.invoiceRukuRelList = this.invoiceRukuRelList;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAction(this.url.edit, this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit('ok');
            });
          } else {
            addAction(this.url.add, this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$emit('ok');
            });
          }
        }
      });
    },

    getInvoiceInfo(info) {
      this.form.invoiceCode = info.number;
      this.form.totalAmount = info.totalAmount;
      this.form.taxAmount = info.taxAmount;
      this.form.noTaxAmount = info.amount;
      this.form.amount = info.totalAmount;
      this.form.invoiceDate = parseTime(info.date, '{y}-{m}-{d}');
      this.getSupplier(info.sellerName);
    },

    async searchSupplier(queryString) {
      this.loadingSupplier = true;
      if (queryString) {
        let params = {
          "pageNum": 1,
          "pageSize": 20,
          "name": queryString
        };
        getAction("/goodsSupplier/goodsSupplier/list", params).then(response => {
          this.optionsSupplier = response.rows;
          this.loadingSupplier = false;
        });
      } else {
        this.optionsSupplier = [];
        this.loadingSupplier = false;
      }
    },

    getSupplier(supplierName) {
      if (isEmpty(supplierName)) {
        return;
      }
      this.$modal.loading("正在加载供应商信息，请稍候...");
      let params = {
        name: supplierName
      }
      getAction('/goodsSupplier/goodsSupplier/list', params).then(response => {
        this.$modal.closeLoading();
        if (response.rows.length > 0) {
          this.optionsSupplier = response.rows;
          this.form.supplierId = response.rows[0].id;
          this.form.supplierName = response.rows[0].name;
        } else {
          this.$modal.msgError("未找到供应商信息，请手动选择");
        }
      }).catch(() => {
        this.$modal.closeLoading();
      });
    },


    // 小写转为大写
    convertCurrency(money) {
      var cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
      var cnIntRadice = ['', '拾', '佰', '仟']
      var cnIntUnits = ['', '万', '亿', '兆']
      var cnDecUnits = ['角', '分', '毫', '厘']
      // var cnInteger = '整'
      var cnIntLast = '元'
      var maxNum = 999999999999999.9999
      var integerNum
      var decimalNum
      var chineseStr = ''
      var parts
      if (money === '') {
        return ''
      }
      money = parseFloat(money)
      if (money >= maxNum) {
        return ''
      }
      if (money === 0) {
        // chineseStr = cnNums[0] + cnIntLast + cnInteger
        chineseStr = cnNums[0] + cnIntLast
        return chineseStr
      }
      money = money.toString()
      if (money.indexOf('.') === -1) {
        integerNum = money
        decimalNum = ''
      } else {
        parts = money.split('.')
        integerNum = parts[0]
        decimalNum = parts[1].substr(0, 4)
      }
      if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0
        var IntLen = integerNum.length
        for (var i = 0; i < IntLen; i++) {
          var n = integerNum.substr(i, 1)
          var p = IntLen - i - 1
          var q = p / 4
          var m = p % 4
          if (n === '0') {
            zeroCount++
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0]
            }
            zeroCount = 0
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m]
          }
          if (m === 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q]
          }
        }
        chineseStr += cnIntLast
      }
      if (decimalNum !== '') {
        var decLen = decimalNum.length
        for (i = 0; i < decLen; i++) {
          n = decimalNum.substr(i, 1)
          if (n !== '0') {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i]
          }
        }
      }
      if (chineseStr === '') {
        // chineseStr += cnNums[0] + cnIntLast + cnInteger
        chineseStr += cnNums[0] + cnIntLast
      }
      return chineseStr
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getBuyStoreDetailList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    getBuyStoreDetailList() {
      this.detailListLoading = true;
      getAction(this.url.buyStoreDetailList, this.queryParams).then(response => {
        this.detailListLoading = false;
        this.buyStoreDetailList = response.rows;
        for (let i = 0; i < this.buyStoreDetailList.length; i++) {
          this.buyStoreDetailList[i].invoiceTemp = this.buyStoreDetailList[i].invoiceRemain;
        }
        this.total = response.total;
      })
    },

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "invoiceTemp" || column.property === "invoiceRemain") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },

    getSummariesRel(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "amount") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length;
      this.selectRows = selection;
    },




    handleAddStoreList(){
      if (this.selectRows.length === 0) {
        this.$message.warning("请选择要添加的入库信息");
        return;
      }

      // invoiceTemp 不能为0
      for (let i = 0; i < this.selectRows.length; i++) {
        if (this.selectRows[i].invoiceTemp === 0) {
          this.$message.warning(this.selectRows[i].params.goodsName+"的开票金额不能为0");
          return;
        }
      }
      let params = {};
      params.rukumingxiList = this.selectRows;
      addAction(this.url.addRukumingxiList, params).then(response => {
        this.getBuyStoreDetailList();
        this.getInvoiceRukuRelList();
      })

    },

    getInvoiceRukuRelList(){
      this.invoiceRukuRelLoading = true;
      getAction(this.url.invoiceRukuRelList, this.relQueryParams).then(response => {
        this.invoiceRukuRelLoading = false;
        this.invoiceRukuRelList = response.rows;
        this.total = response.total;
        this.form.totalAmount=this.sumTotalMoney();
      })
    },


    sumTotalMoney() {
      let totalMoney = 0;
      for (let j = 0; j < this.invoiceRukuRelList.length; j++) {
        totalMoney = accAdd(totalMoney, this.invoiceRukuRelList[j].amount)
      }
      return totalMoney;
    },




    /** 删除按钮操作 */
    handleDeleteRel(row) {
      const ids = row.id;
      deleteAction(this.url.removeRel, ids).then(response => {
        this.getBuyStoreDetailList();
        this.getInvoiceRukuRelList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },




  }
};
</script>
